// 开发环境

import { spawn } from 'child_process'
import electron from 'electron'
import { join } from 'node:path'
import fs from 'node:fs'

export const ElectronDevPlugin = () => {
  return {
    name: 'electron-dev-plugin',
    configureServer(server) {
      server.httpServer.once('listening', (req, res) => {
        const addressInfo = server.httpServer.address()
        console.log(`Electron Dev Server Listening on ${addressInfo.port}`)
        const IP = 'http://localhost:' + addressInfo.port
        const mainPath = join(__dirname, '../electron/main.js')
        let ElectronProcess = spawn(electron, [mainPath, IP])
        fs.watchFile(mainPath, () => {
          ElectronProcess.kill()
          ElectronProcess = spawn(electron, [mainPath, IP])
        })
        ElectronProcess.stdout.on('data', (data) => {
          console.log(data.toString())
        })
      })
    },
  }
}
